package com.pentofab.payrollmanagement.ui.controller;

import java.net.URL;
import java.util.ArrayList;
import java.util.ResourceBundle;

import javafx.beans.value.ChangeListener;
import javafx.beans.value.ObservableValue;
import javafx.collections.FXCollections;
import javafx.collections.ObservableList;
import javafx.event.ActionEvent;
import javafx.fxml.FXML;
import javafx.fxml.Initializable;
import javafx.scene.Parent;
import javafx.scene.control.CheckBox;
import javafx.scene.control.ChoiceBox;
import javafx.scene.control.TableColumn;
import javafx.scene.control.TableView;
import javafx.scene.control.cell.PropertyValueFactory;
import javafx.scene.layout.VBox;

import com.pentofab.payrollmanagement.application.PayrollApplicationFactory;
import com.pentofab.payrollmanagement.dao.LeaveDAO;
import com.pentofab.payrollmanagement.dao.model.Company;
import com.pentofab.payrollmanagement.dao.model.Holiday;
import com.pentofab.payrollmanagement.dao.model.HolidaysDetail;
import com.pentofab.payrollmanagement.dao.model.UserAccounts;
import com.pentofab.payrollmanagement.exception.BusinessException;
import com.pentofab.payrollmanagement.ui.control.CustomTextField;
import com.pentofab.payrollmanagement.utilities.PayRollUtility;

public class HolidaysController extends AbstractUIController implements
	Initializable, FormValidator{

	@FXML
	TableView<HolidaysDetail> tableView;
	@FXML
	private TableColumn<HolidaysDetail, String> date;

	@FXML
	private ChoiceBox<String> from_date;
	
	@FXML
	CheckBox isNationalHoliday;
	@FXML
	private ChoiceBox<String> from_month;

	@FXML
	private ChoiceBox<String> from_year;

	@FXML
	private TableColumn<HolidaysDetail, String> reason;
	
	@FXML
	private CustomTextField occasion;

	@FXML
	private VBox root;
	
	private LeaveDAO leaveDAO = PayrollApplicationFactory.getLeaveDAO();
	private Company company;
	private UserAccounts userAccounts;
	
	private ArrayList<String> fromMonthDaysList = new ArrayList<String>();

	public void delete(ActionEvent event) {

		if(tableView.getSelectionModel().getSelectedIndex() < 0){
			showError(UIMessages.SELECT_AN_ENTRY_TO_DETETE);
			return;
		}
		
		try {
			
			if(showConfirmDialog(String.format(UIMessages.CONFIRM_DELETE, "Holiday")))
				leaveDAO.deleteHoliday(tableView.getSelectionModel().getSelectedItem().getDate());
			
		} catch (BusinessException e) {
			showError(e.getMessage());
		}
		refreshUI();
	
	}

	public void goBack(ActionEvent event) {

		if (getParent() != null && getParent().length() > 0) {
			PayrollApplicationFactory.getMainController().showScreen(
					getParent(), false);
		}
	
	}
	public void add() {
		
		String validationMsg = getValidationMessage();
		
		if(!validationMsg.equals("")){
			showError(validationMsg);
			return;
		}
		String holiday = from_date.getSelectionModel().getSelectedItem()
				+ "-"
				+ (from_month.getSelectionModel()
						.getSelectedIndex() + 1 )
				+ "-"
				+ from_year.getSelectionModel()
						.getSelectedItem();
		try {
		
			if(PayRollUtility.compareDateWithToday(holiday) < 0){
				if(!showConfirmDialog("You are marking a past date as holiday. please confirm.")){
					
					refreshUI();
					return;
				}
			}
				leaveDAO.addholiday(holiday, occasion.getText(),isNationalHoliday.isSelected());
				showInfo(String.format("%s is successfully added to Holidats list.", holiday));
				
		} catch (BusinessException e) {
			showError(e.getMessage());
		}
		refreshUI();
	}
	public void reset() {
		
		System.out.println("resdasffhjfjaskl");
		refreshUI(company,userAccounts);
	}
	@Override
	public Parent getView() {
		return root;
	}

	@Override
	public String getTitle() {
		return "Holidays";
	}
	
	@Override
	public void refreshUI(Object... args) {
		
		if (args != null && args.length > 0) {
			Company company = (Company) args[0];
			this.company = company;
			
			if(args.length > 1 && args[1] instanceof UserAccounts){
				userAccounts = (UserAccounts) args[1];
			}
		}
		populateHolidaysTable();
		from_date.getSelectionModel().clearSelection();
		from_month.getSelectionModel().clearSelection();
		from_date.getSelectionModel().clearSelection();
		
		isNationalHoliday.setSelected(false);
		int year = PayRollUtility.getYear() - 1;
		ArrayList<String> yearList = new ArrayList<String>();
		for (int i = 0; i < 5; i++) {
			yearList.add(year + "");
			year++;
		}
		year = PayRollUtility.getYear();
		from_year.getItems().addAll(yearList);
		from_year.getSelectionModel().select(year+"");
		occasion.clear();
	}
	@Override
	public void initialize(URL arg0, ResourceBundle arg1) {
		iniTableProps();
		
		from_year.getSelectionModel().selectedIndexProperty()
		.addListener(new ChangeListener<Number>() {

			@Override
			public void changed(ObservableValue arg0, Number arg1,
					Number arg2) {

				from_month.getSelectionModel().clearSelection();
			}

		});
		
		from_month.getSelectionModel().selectedIndexProperty()
		.addListener(new ChangeListener<Number>() {

			@Override
			public void changed(ObservableValue arg0, Number arg1,
					Number arg2) {

				if(from_year.getSelectionModel().getSelectedIndex() < 0){
					from_month.getSelectionModel().clearSelection();
					return;
				}
				
				from_date.getSelectionModel().clearSelection();
				from_date.getItems().removeAll(fromMonthDaysList);
				fromMonthDaysList.clear();
				System.out.println(from_date.getItems());
				int fromMaxDay = PayRollUtility.getMaxDayofMonth(Integer
						.parseInt(from_year.getSelectionModel()
								.getSelectedItem()), from_month
						.getSelectionModel().getSelectedIndex());
				for (int i = 1; i <= fromMaxDay; i++) {

					fromMonthDaysList.add(i + "");
				}
				from_date.getItems().addAll(fromMonthDaysList);

			}

		});
		
		
	}

	private void iniTableProps() {

		date.setCellValueFactory(new PropertyValueFactory<HolidaysDetail, String>(
						"date"));
		reason.setCellValueFactory(new PropertyValueFactory<HolidaysDetail, String>(
				"reason"));
	}
	
	private void populateHolidaysTable() {

		PayRollUtility.debug("===================== populateLeaveTable start =====================");

		tableView.getItems().clear();
		ObservableList<HolidaysDetail> data = FXCollections.observableArrayList();
		try {
			ArrayList<Holiday> holidayList = leaveDAO.getHolidays();
			if(holidayList == null){
				return;
			}
			data.addAll(HolidaysDetail.getLeaveDetailList(holidayList));
		} catch (BusinessException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		PayRollUtility.debug("data  : " + data);
		tableView.setItems(data);

		PayRollUtility
				.debug("===================== populateLeaveTable end =====================");

	}
	
	@Override
	public String getValidationMessage() {

		if (from_year.getSelectionModel().getSelectedIndex() < 0) {
			return UIMessages.FROM_YEAR;
		}
		if (from_month.getSelectionModel().getSelectedIndex() < 0) {
			return UIMessages.FROM_MONTH;
		}
		if (from_date.getSelectionModel().getSelectedIndex() < 0) {
			return UIMessages.FROM_DAY;
		}
		
		if(occasion.getText().trim().equals(""))
			return UIMessages.OCCATION_IS_EMPTY;
		return "";

	}

	@Override
	public boolean isValid() {
		return false;
	}
}
